package pikasial.fs;

import java.io.File;
import java.io.IOException;

import pikasial.images.ImageContainer;
import pikasial.images.PikImage;

public class FSOperations {

	public static void renameAllImages(ImageContainer ic,String baseName,char separatorChar)
			throws IOException, SecurityException {
		int i=1;
		for (PikImage pik : ic.getAllImages()) {
			String name = pik.getPath().substring(0,pik.getPath().lastIndexOf('/'));
			name += baseName+separatorChar+i++;
			FSOperations.renameImage(pik, name);
		}
	}

	public static void renameImage(PikImage pik,String name) throws IOException,SecurityException {
		int lastSlash = name.lastIndexOf(File.separator);
		if (lastSlash != -1) {
			deplacerImage(pik,new Dossier(new File(name.substring(0, lastSlash))));
		} else {
			String path = pik.getPath().substring(0,pik.getPath().lastIndexOf('/'));
			File f = new File(path,name);
			if (!pik.getJavaFile().renameTo(f)) {
				throw new IOException("Impossible de créer le fichier de destination "+f.getPath());
			}
		}
	}

	public static void deplacerImage(PikImage pik, Dossier d) throws IOException,SecurityException {
		pik.moveFileTo(d.getJavaFile());
	}

	public static void supprimerImage(PikImage pik) throws SecurityException {
		if (!pik.getJavaFile().delete())
			throw new SecurityException("Impossible de supprimer le fichier "
					+pik.getPath()+"! Vérifiez vos droits sur ce fichier !");
	}


}
